var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64.js');
var app = getApp();
var page = 1;
var inviteuid = '';

var hb_info = '';

var screen_w = 320;
var screen_h = 568;

var timer = '';
// 八戒---------

var distant = 0;
var price = 0;
var hot = 0;
// ---------------
Page({
  data: {
    util: util,
    tc: 1,
    org_name: '',
    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    screen_w: 320,
    tagTitle_bg_w: 40,

    view_order: '', //视图顺序
      logo_urls: '',//顶图
      swiperImgUrls: [],//轮播图
      swiperImgUrls2: [],//轮播图2
      swiperImgUrls3: [],//轮播图3
      gonggaoList: [],//公告
      topmenuInfos: [],//顶部分类菜单
      tietu_urls: '',//贴图区
      zixunfenlei: '', //咨询分类
      top_menu_bg_color: '#fafafa',//顶部菜单背景颜色
      top_menu_item_w: 70, //
      top_menu_img_w_h: 37.5,//顶部菜单图片宽高

      menu_item_w: 90, //
      menu_img_w_h: 37.5,//菜单图片宽高

      tuijianData:[],//店长推荐（置顶）
      tuijianOb: '',

      djJingxuanData: [],//冬季精选
      jingxuanOb: '',

      xinpin_data: [],//新品
      xinpinOb: '',

      goodsTypeArray: '',//商品分类区
      fenleiOb: '',

      mendian_data:'',//门店／经销商
      ghsData:[],

      indicatorDots: true,
      indicatorDots2: false,
      autoplay: true,
      interval: 4000,
      duration: 600,
      startTime:0, 

      userInfo: null,
      token: '',
      loginuid:'',
      
      userphotos: [],

      isIphone:false,

      isShow: false,

      itemViewWidth: 105,
      itemViewHeight: 158,

      goodsImgView_h: 160,

      swiper_h: 160,

      contact_phone: '',

      hongbaoInfo: '',
      curTime: 0,
      colorIndex: 0,

      guanggao_link: '',

      gg_img_w: 290,
      gg_img_h: 290*4/3,

      markers: [{
        iconPath: "/images/map_sign.png",
        id: 0,
        latitude: 23.016357,
        longitude: 113.103185,
        width: 20,
        height: 35
      }],

      colorSet: '',

      animation:'',//广告动画
      screen_h: 480,


      AbanList: [],
      BbanList:[],
      guojibanList:[],
      fenlei0class: "font-weight:bold;color:#4595FD;",
      fenlei1class: "",
      fenlei2class: "",

      line0: "height:8rpx;",
      line2: "",
      line3: "",

      myhao: '',

      hide_chooseview:true,//简繁体选择
      oldData:'',
      artArray:'',
      topNum: 0,
   
  },

  onLoad: function (data) {
    console.log("xxxxxxxxxxxxxxxxxxxxxxx", data);
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      oldData:data,
    });
    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });

    var indexshow = app.globalData.indexshow;
    console.log("indexshow====", indexshow);
    if(indexshow){
      that.setData({
        hide_chooseview:true
      });
      app.globalData.indexshow = false;
    }else{
      that.setData({
        hide_chooseview:false
      });
    }

    hb_info = '';
    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      wx.setNavigationBarTitle({
        title: res.uname,
      });
  
      that.setData({
        org_name: res.uname
      })
    });
    
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('index/index', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        screen_w = res.windowWidth;
        screen_h = res.windowHeight;
        var width = (res.windowWidth / 2) - (res.windowWidth / 8);
        var height = width + 1;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone: isiPhone,
          isIphone_x: isIphone_x,
          screen_w: screen_w,
          screen_h: res.windowHeight,
          tagTitle_bg_w: (screen_w/320) * 40,
          itemViewWidth: width,
          itemViewHeight: height,
          goodsImgView_h: (screen_w - 30) / 2,
          swiper_h: screen_w / 2,
          top_menu_item_w: (screen_w - 24) / 4,
          top_menu_img_w_h: 37.5 * (screen_w / 320),

          menu_item_w: (screen_w - 24) / 4,
          menu_img_w_h: 70 * (screen_w / 320),

          gg_img_w: screen_w - 30,
          gg_img_h: (screen_w - 30) * 4 / 3,
        });
        if (util.orgid == '18681') {
          that.setData({
            swiper_h: screen_h - screen_w - (isIphone_x ? 70 : 50)
          })
        }
      }
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    }) 

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        that.setData({
          isShow: responseData.data.isShow
        });
    
      }
    });
 

    // 1 - 轮播图; 2 - 顶图; 3 - 顶部菜单; 4 - 精选区
    // 5 - 推荐区; 6 - 新品区; 7 - 分类区; 8 - 经销商／门店区
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "areaorder",
        "uid": util.orgid
      },
      success: function (responseData) {
        console.log("视图顺序：", responseData.data)
        that.setData({
          view_order: responseData.data
        });

        //读取企业logo
        that.loadSwiperImage(2);
        //读取首页顶部菜单
        that.loadSwiperImage(3);
        //读取幻灯片图片链接
        that.loadSwiperImage(1);
        //读取精选数据
        // that.loadSwiperImage(4);
        //读取推荐数据
        // that.loadSwiperImage(5);
        //读取新品数据
        // that.loadSwiperImage(6);
        //读取商品分类便签名
        // that.loadSwiperImage(7);
        //读取门店
        // that.loadSwiperImage(8);
        //读取幻灯片图片链接2
        that.loadSwiperImage(10);
        //读取幻灯片图片链接3
        that.loadSwiperImage(11);
        //读取幻咨询分类
        // that.loadSwiperImage(12);
        //读取公告链接
        that.loadSwiperImage(13);
      }
    });
    
    //是否是从分享进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    
    //读取登录用户信息
    app.LoginUserInfo(function(res){   
      console.log("登录用户信息：", res);
      if(res && res != -1){
        that.setData({
          loginuid: res.uid,
          token: res.token
        });
        //设置用户信息
        app.GetUserInfo(res.uid, function (res) {
          var up = '';
          if (res.photo){
            up = res.photo.split(',');
          }
          //更新数据
          that.setData({
            userInfo:res,
            userphotos: up
          })
          // //获取定位
          // that.getMyLocation();    

        });
      }       
    }, inviteuid);


    //获取关于等信息
    app.getAllAbout('contact', function(res){
      that.setData({
        contact_phone: res
      })
    });

    //获取今期之星艺术家信息
    that.getRecYsj();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      console.log("color========",color);
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    this.animation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: 300,
      /**
       * http://cubic-bezier.com/#0,0,.58,1  
       *  linear  动画一直较为均匀
       *  ease    从匀速到加速在到匀速
       *  ease-in 缓慢到匀速
       *  ease-in-out 从缓慢到匀速再到缓慢
       * 
       *  http://www.tuicool.com/articles/neqMVr
       *  step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
       *  step-end   保持 0% 的样式直到动画持续时间结束        一闪而过
       */
      timingFunction: 'linear',
      // 延迟多长时间开始
      delay: 0,
      /**
       * 以什么为基点做动画  效果自己演示
       * left,center right是水平方向取值，对应的百分值为left=0%;center=50%;right=100%
       * top center bottom是垂直方向的取值，其中top=0%;center=50%;bottom=100%
       */
      transformOrigin: 'center bottom 0',
    });
  },

  onShow: function(){


  },




  resetNavColor: function(){
    var bg_color = '#cccc00';
    var fg_color = '#ffffff';

    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

  },

  getGoodsClassly: function () {
    //读取商品分类数据
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodstype",
        //"tc": that.data.tc
      },
      success: function (responseData) {
        console.log("商品分类数据：", responseData.data);
        var goodsType = responseData.data;
        if (goodsType.msg) {
          wx.hideLoading();
        } else {
          that.setData({
            goodsTypeArray: goodsType
          })
          for (var i = 0; i < goodsType.length; i++) {
            that.loadFenleiGoodsData(goodsType[i], i);
          }
        }
      }
    });
  },



//index 001  幻灯片数据
  loadSwiperImage: function(index){
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": index,
      "tc": that.data.tc
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log(index + "-- swiper image:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          if (index == 2) {
            result.forEach(function (m, i) {
              var col = parseInt(m.col);
              col = col == 0 ? 1 : col;
              result[i].img_w = screen_w / col;
              console.log("顶图宽：" + m.img_w + "; col = " + col);
            });
            that.setData({
              logo_urls: result
            })

            that.logo_urlsTC();
          } else if (index == 3) {
            var colCount = result[0].col == '0' ? 4 : parseInt(result[0].col);
            var topItem_w = (screen_w - 3) / colCount;
        
            that.setData({
              top_menu_item_w: topItem_w,
              topmenuInfos: result,
              top_menu_bg_color: result[0].bgcolor ? result[0].bgcolor : '#fafafa',
            });
      
            // that.topmenuInfosTC();
            console.log('that.data.topmenuInfos------------->>>>', that.data.topmenuInfos)
          } else if(index == 1){
            that.setData({
              swiperImgUrls: result
            });
          } else if (index == 10) {
            that.setData({
              swiperImgUrls2: result
            });
          } 
          else if (index == 11) {
            that.setData({
              swiperImgUrls3: result
            });
          }
            else if (index == 4) {
            var item_data = result[0];
            var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
            var w_h = (screen_w - (colCount + 1) * 5) / colCount;
            item_data.w_h = w_h;
            that.setData({
              jingxuanOb: item_data
            })
            console.log("精选课程", item_data)
            that.loadGoodsListData(0, 1);
          } else if (index == 5) {
            var item_data = result[0];
            var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
            var w_h = (screen_w - (colCount + 1) * 7) / colCount;
            item_data.w_h = w_h;
            that.setData({
              tuijianOb: item_data
            })
            that.loadGoodsListData(1, 0);
            if(util.orgid=='17758'){
              that.setData({
                tuijianOb: that.splitNavtitle(result),
                tuijianData: that.splitNavtitle(result)
              })
            }
          } else if (index == 6) {
            var item_data = result[0];
            var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
            var w_h = (screen_w - (colCount + 1) * 7) / colCount;
            item_data.w_h = w_h;
            that.setData({
              xinpinOb: item_data
            })
            that.loadGoodsListData(0, 0);
          } else if (index == 7) {
            var item_data = result[0];
            var colCount = item_data.col == '0' ? 1 : parseInt(item_data.col);
            var w_h = (screen_w - (colCount + 1) * 7) / colCount;
            item_data.w_h = w_h;
            that.setData({
              fenleiOb: item_data
            })
            //读取商品分类数据
            that.getGoodsClassly();
          } else if (index == 8) {//门店
            that.setData({
              shopViewName: result[0].navtitle,
              mendian_data: result
            });
            console.log('mendian:', result)
          } else if (index == 11) {
            result.forEach(function (m, i) {
              var col = parseInt(m.col);
              col = col == 0 ? 1 : col;
              result[i].img_w = screen_w / col;
              console.log("贴图宽：" + m.img_w + "; col = " + col);
            });
            that.setData({
              tietu_urls: result
            })
            if (util.orgid == '17758') {
              that.setData({
                tietu_urls: that.splitNavtitle(result)
              })
            }
          }else if (index == 12) {
            console.log("index == 12",result);
            result.forEach(function (m, i) {
              var col = parseInt(m.col);
              col = col == 0 ? 1 : col;
              result[i].img_w = screen_w / col;
              console.log("贴图宽：" + m.img_w + "; col = " + col);
            });

            that.setData({
              zixunfenlei: result,
            })

            if (util.orgid == '17758') {
              that.setData({
                zixunfenlei: that.splitNavtitle(result),
              });
            }

            console.log("zixunfenlei", that.data.zixunfenlei);
          } else if (index == 13) {
            that.setData({
              gonggaoList: result
            })
            console.log("13=============",that.data.gonggaoList);
          }
        }
        wx.hideLoading();
      }
    });
  },



  goAtherPage: function(e){
      app.saveFormId(e.detail.formId);
      var url = e.currentTarget.dataset.link;
      
      wx.navigateTo({url: url})
  },
  goAtherPageRedirect: function(e){
      app.saveFormId(e.detail.formId);  
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },
  goToWangzhan:function(e){
      console.log(e);
      var url = e.currentTarget.dataset.link;
      var url_base64 = base64.encode(url);
      var path = "/pages/live_play_page/live_play_page?weburl=" + url_base64;
      wx.navigateTo({ url: path })
  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
   
    return {
      title: that.data.org_name,
      path: '/pages/index/index?&inviteuid=' + inviteuid
    };

  },
  

  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    console.log("e====",e)
    var path = e.detail.value.nav_path;
    console.log("path", e.detail.value)
    console.log("path",path)
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({ url: path });
      }

    }

    path = e.detail.value.page_path;
    if (path) {
      wx.navigateTo({ url: path });
    }
  },

  makeCallPhone:function(e) {
    app.saveFormId(e.detail.formId);
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success:function(e){
        console.log("make call success:", JSON.stringify(e));
      },
      fail:function(e){
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },




  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },


  //标题中英切换
  logo_urlsTC:function(){
    var that= this;
    var arr = that.data.logo_urls;

    that.setData({
      logo_urls: arr
    })
  },

  splitNavtitle: function (navList) {
    var that = this;
    for (var i = 0; i < navList.length; i++) {
      let title = navList[i].navtitle;
      if (title.indexOf(":") > 0) {
        let miniArr = title.split(':')
        if (miniArr.length == 2) {
          if (!navList[i].summary) {
            navList[i].summary = '';
          }
          navList[i].navtitle = miniArr[0];
          navList[i].summary = miniArr[1];
          console.log('navtitle.summary', navList[i].summary)

        } else {

        }
        console.log('navtitle.summary', navList[i].summary)
      } else {
        if (!navList[i].summary) {
          navList[i].summary = '';
        }
        console.log('navtitle.summary', navList[i].summary)
      }

    }
    return navList
  },

  // 读取门店
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据17784：", result);
        that.setData({
          ghsData: that.data.ghsData.concat(result)
        });
        that.loadGoodsToGHS();
      }
    });
  },

  loadGoodsToGHS: function () {
    console.log("loadGoodsToGHS17784：");
    var that = this;

    that.getGoodsClassly();
  },


  distantOrder: function () {
    hot = 0;
    page = 1;
    if (distant == 0 || distant == 1) {
      distant = 2;
    } else {
      distant = 1;
    }
    this.setData({
      hotOrder: hot,
      distantOrder: distant,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },
  priceOrder: function () {
    hot = 0;
    page = 1;
    if (price == 0 || price == 1) {
      price = 2;
    } else {
      price = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },

  hotOrder: function () {
    price = 0;
    page = 1;
    if (hot == 0 || hot == 1) {
      hot = 2;
    } else {
      hot = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      toporder: '',
      hidecata: true
    });
    // this.loadGoodsListData(1);
  },

  swiperAction: function(e) {
    var that = this;
    var data = e.currentTarget.dataset.info;
    app.saveFormId(e.detail.formId);
    console.log("swiper data:", data);
    if (data) {
      var go_type = data.type;
      var go_id = data.data;
      if (go_type == "topic") { //去详情页
        var url = "/pages/detail/detail?topicid=" + go_id;
        wx.navigateTo({
          url: url
        })
      } else if (go_type == "url") {
        var url = go_id;
        if (url.indexOf('/pages/') >= 0) {
          wx.navigateTo({
            url: url
          })
        } else if (url.indexOf('showToast') >= 0) {

        }
      } else {
        // app.dialog('未定义跳转：' + go_type + '--' + go_id, 'success');
      }
    }
  },


  //点击切换语言
  qiehuanTap:function(e){
    console.log(e);
    var that = this;
    var num = e.currentTarget.dataset.num;
    var res = app.set_tc(num);
    that.setData({
      tc: num,
      hide_chooseview:false
    });
    that.onLoad(that.data.oldData);
   
  },



   //获取艺术家
  getRecYsj:function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getRecYsj",
      },
      success: function (responseData) {
        console.log("getRecYsj===", responseData);
        if(responseData.data.res == false){

        }else{
          let resData = responseData.data;
          resData.photoArr = resData.photo.split(',');
          that.setData({
            artArray:responseData.data,
          })

        }
 
      }
    });
  },


  // 滚动到顶部
  backTop:function(){
     this.setData({
      topNum: this.data.topNum = 0
    });

  },

  copyLink: function (e) {
    var that = this;
    wx.setClipboardData({
      data: e.currentTarget.dataset.link,
      success: function (res) {
        wx.showToast({
          title: that.data.tc == 1 ? '已複制到剪貼板' : '已复制到剪贴板',
        })
      }
    })
  },

  
})
